<template>
  <div>
    <my-breadcrumb :items="['用户管理', '公众号用户']"></my-breadcrumb>
    <user-search @toSearch="toSearch" @getAll="getAll"/>
    <div style="position: relative;">
      <Table :columns="userData" :data="userList"></Table>
    </div>
    <page-info :page="page" @pageNumChange="pageNumChange" @pageSizeChange="pageSizeChange"></page-info>
    <Modal v-model="showSetup" @on-ok="updateType" title="设置用户类型" width="700">
      <div style="margin-bottom: 16px;">
        <h3>选择用户体系</h3>
        <RadioGroup v-model="selectSetup">
          <Radio v-for="(setup, index) in setupList" :key="index" :label="setup.id">{{ setup.name }}</Radio>
        </RadioGroup>
      </div>
      <Table :columns="setupColumns" :data="setupList"></Table>
    </Modal>
  </div>
</template>

<script>
import userSearch from './userSearch'
import pageInfo from '../../common/pageInfo'
export default {
  name: 'user-list',
  data () {
    return {
      url: {
        userList: '/admin/manager/user/list',
        setupList: '/discount/setup/manage/select/all/branch/customer',
        setLevel: '/discount/setup/manage/set/user/level',
        set: '/distributor/set',
        unbind: '/distributor/invite/user/unbind',
        search: '/branch/user/search'
      },
      userData: [
        {
          title: '微信',
          key: 'nickname',
          width: 150,
          render: (h, params) => {
            let sex = params.row.sex === 1 ? 'male' : params.row.sex === 2 ? 'female' : false
            let color = params.row.sex === 1 ? '#2d8cf0' : params.row.sex === 2 ? '#ed3f14' : ''
            return h('div', {
              style: {
                position: 'relative'
              }
            }, [
              h('Avatar', {
                props: {
                  src: params.row.profilePhotoPath
                }
              }),
              h('span', {
                style: {
                  marginLeft: '8px'
                }
              }, params.row.nickname),
              h('Icon', {
                style: {
                  position: 'absolute',
                  top: '18px',
                  left: '24px',
                  display: sex ? 'block' : 'none'
                },
                props: {
                  type: params.row.sex === 1 ? 'male' : 'female',
                  color,
                  size: 14
                }
              })
            ])
          }
        },
        {
          title: '真实姓名',
          key: 'realName',
          align: 'center',
          width: 100
        },
        {
          title: '联系方式',
          key: 'phone',
          align: 'center',
          width: 130
        },
        {
          title: '价格体系',
          key: 'setup',
          align: 'center'
        },
        {
          title: '所在地区',
          key: 'province',
          align: 'center',
          width: 150,
          render: (h, params) => {
            return h('span', params.row.province + ' ' + params.row.city)
          }
        },
        {
          title: '类型',
          key: 'type',
          align: 'center',
          width: 100,
          render: (h, params) => {
            return h('span', params.row.type === 1 ? '公众号用户' : '分销商客户')
          }
        },
        {
          title: '最后活跃时间',
          key: 'time',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('span', this.setTime(params.row.lastActiveTime))
          }
        },
        {
          title: '操作',
          key: 'do',
          align: 'center',
          width: 110,
          render: (h, params) => {
            if (params.row.type === 1) {
              return h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.setupSet(params.row)
                  }
                }
              }, '设置价格体系')
            } else {
              return h('Poptip', [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  }
                }, '脱离分销商'),
                h('Input', {
                  props: {
                    type: 'password',
                    placeholder: '输入密码脱离分销商'
                  },
                  style: {
                    width: '150px'
                  },
                  on: {
                    input: (e) => {
                      this.password = e
                    }
                  },
                  slot: 'content'
                }),
                h('Button', {
                  props: {
                    type: 'primary'
                  },
                  on: {
                    click: () => {
                      this.$ajax.post(this.url.unbind, {inviteUserId: params.row.id, password: this.password}).then(res => {
                        if (res.data.success) {
                          this.$Message.success('解绑成功')
                          this.getQueryInfo()
                        }
                      })
                    }
                  },
                  slot: 'content'
                }, '确定')
              ])
            }
          }
        },
        {
          title: '设置分销',
          align: 'center',
          render: (h, params) => {
            return h('Button', {
              props: {
                type: 'primary',
                disabled: params.row.isDistributor === 1
              },
              on: {
                click: () => {
                  if (params.row.isDistributor === 1) {
                    return
                  }
                  this.discount = params.row.doubleDiscount
                  this.nowId = params.row.id
                  this.$Modal.confirm({
                    title: '设置分销折扣',
                    render: (h) => {
                      return h('div', [
                        h('span', '分销折扣：'),
                        h('InputNumber', {
                          props: {
                            value: this.discount,
                            placeholder: '请输入分销折扣',
                            min: 0
                          },
                          on: {
                            input: (val) => {
                              this.discount = val
                            }
                          }
                        }),
                        h('p', {
                          style: {
                            marginTop: '16px'
                          }
                        }, [
                          h('span', '二级密码：'),
                          h('Input', {
                            props: {
                              type: 'password',
                              placeholder: '输入二级密码才可设置分销商'
                            },
                            on: {
                              input: (e) => {
                                this.password = e
                              }
                            },
                            style: {
                              width: '200px'
                            }
                          })
                        ])
                      ])
                    },
                    onOk: () => {
                      this.setDistributor()
                    }
                  })
                }
              }
            }, params.row.isDistributor === 0 ? '设置分销商' : '已是分销商')
          }
        },
        {
          title: '查看订单',
          render: (h, params) => {
            return h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              on: {
                click: () => {
                  this.$router.push({path: '/branch/order/list', query: {id: params.row.id}})
                }
              }
            }, '查看')
          }
        }
      ],
      userList: [],
      // 设置用户类型
      setupColumns: [
        {
          title: '体系名称',
          key: 'name'
        },
        {
          title: '体系描述',
          key: 'description'
        },
        {
          title: '折扣比例',
          key: 'branchDiscount',
          width: 100,
          render: (h, params) => {
            return h('span', {
              style: {
                fontWeight: '800',
                color: '#19be6b'
              }
            }, params.row.branchDiscount + '%')
          }
        },
        {
          title: '期望利润',
          key: 'expectedProfit',
          render: (h, params) => {
            return h('span', {
              style: {
                color: '#19be6b',
                fontWeight: '800'
              }
            }, params.row.expectedProfit ? params.row.expectedProfit + '%' : '')
          }
        },
        {
          title: '最低利润',
          key: 'minProfit',
          render: (h, params) => {
            return h('span', {
              style: {
                color: '#ed3f14',
                fontWeight: '800'
              }
            }, params.row.minProfit ? params.row.minProfit + '%' : '')
          }
        }
      ],
      setupList: [],
      setupIdArr: [],
      showSetup: false,
      selectSetup: null,
      oldSetup: null,
      nowId: null,

      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tabLoading: true,

      discount: null,
      password: '',
      term: null,
      activeUrl: ''
    }
  },
  methods: {
    /**
     * @param id 用户id
     * 设置用户类型
     */
    setupSet (row) {
      this.nowId = row.id
      this.selectSetup = row.branchCustomerId
      this.oldSetup = row.branchCustomerId
      this.showSetup = true
    },
    /**
     * 提交用户设置
     */
    updateType () {
      if (this.selectSetup === this.oldSetup) {
        return
      }
      this.$ajax.post(this.url.setLevel, {userId: this.nowId, branchCustomerId: this.selectSetup}).then(res => {
        if (res.data.success) {
          this.$Message.success('设置成功')
          this.getQueryInfo(this.page.pageNum, this.page.pageSize)
        }
      })
    },

    setDistributor () {
      let params = {
        discount: this.discount,
        userId: this.nowId,
        password: this.password
      }
      this.$ajax.post(this.url.set, params).then(res => {
        if (res.data.success) {
          this.$Message.success('请分销商在手机端重新设置分销价')
          this.getQueryInfo(this.page.pageNum, this.page.pageSize)
        }
      })
    },

    initPage () {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    },
    toSearch (data) {
      this.activeUrl = this.url.search
      this.initPage()
      this.term = data
      this.getQueryInfo(this.page.pageNum, this.page.pageSize, this.term)
    },
    getAll () {
      this.term = null
      this.initPage()
      this.getQueryInfo(this.page.pageNum, this.page.pageSize, this.term)
    },

    setTime (val) {
      var time = new Date(val)
      var y = time.getFullYear()
      var m = time.getMonth() + 1
      var d = time.getDate()
      var h = time.getHours()
      var mm = time.getMinutes()
      var s = time.getSeconds()
      return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s
    },
    pageNumChange (page) {
      this.tabLoading = true
      this.getQueryInfo(page.pageNum, page.pageSize, this.term)
    },
    pageSizeChange (page) {
      this.tabLoading = true
      this.getQueryInfo(page.pageNum, page.pageSize, this.term)
    },
    getQueryInfo (pageNum, pageSize, term) {
      let params
      if (term) {
        this.activeUrl = this.url.search
        params = {
          ...term,
          pageQuery: {
            pageNum,
            pageSize
          }
        }
      } else {
        this.activeUrl = this.url.userList
        params = {
          pageSize,
          pageNum
        }
      }
      this.$ajax.post(this.activeUrl, JSON.stringify(params)).then(res => {
        res.data.data.pageInfo.list.forEach(item => {
          if (item.type === 1) {
            item.setup = this.setupIdArr['I' + item.branchCustomerId].name
            item.doubleDiscount = this.setupIdArr['I' + item.branchCustomerId].branchDiscount * 2
          }
        })
        this.userList = res.data.data.pageInfo.list
        this.page.total = res.data.data.pageInfo.total
        this.tabLoading = false
      })
    }
  },
  components: {
    userSearch,
    pageInfo
  },
  created () {
    this.$ajax.get(this.url.setupList).then(res => {
      if (res.data.success) {
        this.setupList = res.data.data
        res.data.data.forEach(item => {
          this.setupIdArr['I' + item.id] = item
        })
        this.getQueryInfo(this.page.pageNum, this.page.pageSize)
      }
    })
  }
}
</script>

<style scoped>

</style>
